package order

import (
	"errors"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"higame/config"
	mongodb "higame/modules/db"
	"higame/routes/user"
)

type Status string
type PayType string
type Type string

const (
	FK          Status  = "付款"
	FH          Status  = "发货"
	SH          Status  = "收货"
	QX          Status  = "取消"
	IntegralPay PayType = "积分付款"
	AliPay      PayType = "支付宝付款"
	WechatPay   PayType = "微信付款"
	Goods       Type    = "积分兑换"
	Game        Type    = "游戏装备"
)

var db = mongodb.GetInstance()
var colName = config.Db.Collection.Order

type Express struct {
	Name   string `json:"name" bson:"name" form:"name"`
	Number string `json:"number" bson:"number" form:"number"`
}
type Schema struct {
	ID          primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	Seller      string             `json:"seller" bson:"seller" form:"seller" binding:"required"`
	Buyer       string             `json:"buyer" bson:"buyer" form:"buyer" binding:"required"`
	Quantity    int64              `json:"quantity" bson:"quantity" form:"quantity" binding:"required"`
	OrderID     string             `json:"order_id" bson:"order_id" form:"order_id"`
	AddTime     int64              `json:"add_time" bson:"add_time" form:"add_time"`
	FHTime      int64              `json:"fh_time" bson:"fh_time" form:"fh_time"`
	SHTime      int64              `json:"sh_time" bson:"sh_time" form:"sh_time"`
	QXTime      int64              `json:"qx_time" bson:"qx_time" form:"qx_time"`
	GoodsID     string             `json:"goods_id" bson:"goods_id" form:"goods_id" binding:"required"`
	Title       string             `json:"title" bson:"title" form:"title" binding:"required"`
	MainImage   string             `json:"main_image" bson:"main_image" form:"main_image" binding:"required"`
	Price       float64            `json:"price" bson:"price" form:"price" binding:"required"`
	SourceUrl   string             `json:"source_url" bson:"source_url" form:"source_url" binding:"required"`
	OrderStatus Status             `json:"order_status" bson:"order_status" form:"order_status" binding:"required"`
	Receiver    user.AddressSchema `json:"receiver" bson:"receiver" form:"receiver" binding:"required"`
	PayType     PayType            `json:"pay_type" bson:"pay_type" form:"pay_type" binding:"required"`
	ExpressType Express            `json:"express_type" bson:"express_type" form:"express_type" binding:"required"`
	Remark      string             `json:"remark" bson:"remark" form:"remark" binding:"required"`
	OrderType   Type               `json:"order_type" bson:"order_type" order_type:"type" binding:"required"`
}

func New() *Schema {
	return &Schema{}
}

func Parse(data bson.M) (*Schema, error) {
	u := New()
	if err := db.ToStruct(data, u); err != nil {
		return nil, err
	}
	return u, nil
}

func DeleteOneByOrderID(id string) error {
	b := db.DeleteOne(colName, bson.M{"order_id": id})
	if !b {
		return errors.New("删除失败")
	}
	return nil
}

func AddOne(schema *Schema) error {
	adminI := db.InsertOne(colName, schema)
	if !adminI {
		return fmt.Errorf("添加失败。\n")
	}
	return nil
}
func FindOne(filter interface{}) (*Schema, error) {
	userF := db.FindOne(colName, filter)
	if userF == nil {
		return nil, errors.New("数据不存在！")
	}

	return Parse(userF)
}

func FindOneByOrderID(id string) (*Schema, error) {
	userF := db.FindOne(colName, bson.M{"order_id": id})
	if userF == nil {
		return nil, errors.New("数据不存在！")
	}

	return Parse(userF)
}

func FindMany(pageNum int64, filter interface{}) ([]bson.M, error) {
	pageNum = pageNum - 1
	if pageNum < 0 {
		pageNum = 0
	}
	opts := new(options.FindOptions)
	list := db.FindMany(colName, filter,
		opts.SetSkip(pageNum*20),
		opts.SetLimit(20),
		opts.SetSort(bson.M{
			"add_time": -1,
		}))
	return list, nil
}

func UpdateOneByOrderID(id string, update interface{}) error {
	b := db.UpdateOne(colName, bson.M{
		"order_id": id,
	}, bson.M{
		"$set": update,
	})

	if !b {
		return errors.New("没有修改任何数据")
	}
	return nil
}

func Count(filter interface{}) (int64, error) {
	return db.Count(colName, filter), nil
}


func RestoreQuantity(orderType Type, id string, quantity int64) error {
	dbColName := ""
	filter := bson.M{}
	if orderType == Goods {
		dbColName = config.Db.Collection.Goods
		filter["goods_id"] = id
	} else if orderType == Game {
		dbColName = config.Db.Collection.Trade
		filter["uuid"] = id
	}
	b := db.UpdateOne(dbColName, filter, bson.M{
		"$inc": bson.M{
			"quantity": quantity,
		},
	})

	if !b {
		return errors.New("没有修改任何数据")
	}
	return nil
}
